import http from '../utils/http'
import constant from '../utils/constant'
// import myDatepicker from 'vue-datepicker/vue-datepicker-es6.vue'
import VueFlatPickr from 'vue-flatpickr-component'
import 'flatpickr/dist/flatpickr.css'

export default {
  name: 'searchResult',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      result: {},
      loadingData: false,
      vehicleCores: [],
      hasVehicleCores: false,
      disabled: 'disabled',
      categoriesDrop: true,
      typeDrop: true,
      countryShow: false,
      countriesOptions: undefined,
      selectedCountry: 'US,CA',
      selectedCountryId: 93,
      selectedCountryName: '北美',
      currentCountryIndex: '',
      currentCountryId: '',
      currentLetter: '',
      currentHotLetter: '',
      supplierDrop: true,
      suppliersData: undefined,    // 请求得到的供应商数据
      suppliersArray: undefined,   //根据国家获取供应商
      suppliers: [{
        chinese_name: "Enterprise",
        code: "Enterprise",
        id: 1
      },{
        chinese_name: "爱路美",
        code: "Alamo",
        id: 2
      },{
        chinese_name: "National",
        code: "National",
        id: 3
      }],
      selectedsupplier: {
        chinese_name: "爱路美",
        code: "Alamo",
        id: 2
      },
      selectedCityName: undefined,
      selectedCityCode: undefined,
      selectedCityId: undefined,
      currentShowModal: '',
      searchCityVal: '',
      hotLocations: '',
      currentCityIndex: '',
      currentCityId: '',
      returnCityName: undefined,
      returnCityCode: undefined,
      returnCityId: undefined,
      returnCurrentCityId: undefined,
      returnCurrentCityIndex: undefined,
      returnCurrentSearchCityIndex: undefined,
      hotCityShow: false,
      currentSearchCityIndex: '',
      searchCityData: undefined,
      pickupDate: undefined,
      returnDate: undefined,
      config: {
        minDate: new Date().fp_incr(-1),
        enableTime: true,
        time_24hr: true,
        minuteIncrement: 30
      },
      carsSets: undefined,
      carsCategories: undefined,
      driverAge: undefined,
      ageSelected: undefined,
      typeOptions: [{
        payCode:'ARRIVEPAY',
        payName: '到付'
      },
      {
        payCode: 'PREPAY',
        payName: '预付'
      }],
      selectedType: undefined,
      selectCategories: undefined,
      setCategories: [{
        id: 1,
        code: "7015855",
        english_name: "畅游基本计划",
        chinese_name: "畅游基本计划",
      }, {
        id: 2,
        code: "J0035",
        english_name: "无忧自驾计划",
        chinese_name: "无忧自驾计划",
      }, {
        id: 3,
        code: "J0033",
        english_name: "尊尚自驾计划（4天起）",
        chinese_name: "尊尚自驾计划 (4天起）",
      }, {
        id: 4,
        code: "EC2NA",
        english_name: "基本套餐",
        chinese_name: "基本套餐",
      }, {
        id: 5,
        code: "5030201",
        english_name: "基本套餐",
        chinese_name: "基本套餐",
      }, {
        id: 6,
        code: "1231",
        english_name: "增值套餐C",
        chinese_name: "增值套餐C",
      }, {
        id: 7,
        code: "A03EUJ",
        english_name: "基本套餐",
        chinese_name: "基本套餐",
      }],
      selectedCategoryVal: this.$route.query.setCategoryId,
      carTypeOpt: [{
        code: "0",
        chineseName: "全部车型"
      }],
      selectedTypeVal: '0',
      carSiteOpt: [{
        name: '全部座位',
        value: '0,100'
      }, {
        name: '2-4位',
        value: '2,4',
      }, {
        name: '4-5位',
        value: '4,5',
      }, {
        name: '5-7位',
        value: '5,7',
      }, {
        name: '7位及7位以上',
        value: '7,100',
      }],
      selectedSiteVal: '0,100',
      carPriceOpt: [{
        name: '默认',
        value: 'default'
      },{
        name: '低到高',
        value: 'LowToHigh'
      }, {
        name: '高到低',
        value: 'highToLow'
      }],
      selectedPriceVal: 'default',
      defaultSort: [],
      priceStatu: true
    }
  },
  components: {
    // 'date-picker': myDatepicker,
    'flat-pickr': VueFlatPickr
  },
  created() {
    let that = this

    let pageLoading = this.$message.loading({
      message: '正在加载数据...',
      align: 'center'
    })

    this.requestCountry()
    this.requestSuppliers()
    this.requestSets()
    this.requestCategories()
    this.initDriverAge()

    $.when(this.requestCountry, this.requestSuppliers, this.requestSets, this.requestCategories).then(function() {
      setTimeout(() => {
        that.loadingData = true
        pageLoading.close()
      }, 1000);
    })
    that.selectedsupplier = that.$store.getters.getSuppliersData 
    that.selectedCityName = that.$store.getters.getCarLocation[0]
    that.returnCityName = that.$store.getters.getCarLocation[1]
    
    if(that.$route.query && Object.keys(that.$route.query).length > 0) {
      that.selectedCountryName = that.$route.query.countryName
      that.selectedCountry = that.$route.query.countryCode
      that.selectedCountryId = that.$route.query.countryId
      that.selectedCityId = that.$route.query.pickupLocation
      that.selectedsupplier.id = that.$route.query.supplierId
      that.returnCityId = that.$route.query.returnLocation
      that.pickupDate  = that.$route.query.pickupDate
      that.returnDate = that.$route.query.returnDate
      that.ageSelected = that.$route.query.driveAge+'岁'
      that.selectedType = that.$route.query.type
      that.selectCategories = parseInt(that.$route.query.setCategoryId)
      that.searchResult()
    }
  },

  methods: {
    initDriverAge() {
      let ageArr = [];
      for(let i = 18; i<= 30; i++) {
        if(i == 30) {
          ageArr.push({code: i, value: i+"或" + i +'岁以上'})
        } else {
          ageArr.push({code: i, value:i+"岁"})
        }
      }

      this.driverAge = ageArr
    },
    requestCountry() {
      const that = this
      let defer = $.Deferred()
      http.get(constant.counties, null, function(response) {
        that.$set(that.$data, 'countriesOptions', response.countries)
        defer.resolve()
      }, function(response) {
        console.log(response)
      })

      return defer.promise()
    },

    requestSuppliers() {
      const that = this
      let defer = $.Deferred()
      http.get(constant.suppliers, null, function(response) {
        that.suppliersData = response.suppliers
        defer.resolve()
      }, function(response) {
        console.log(response)
      })

      return defer.promise()
    },

    requestSets() {
      const that = this
      let defer = $.Deferred()
      http.get(constant.carsSets, null, function(response) {
        that.carsSets = response.sets
        defer.resolve()
      }, function(response) {
        console.log(response)
      })

      return defer.promise()
    },

    requestCategories() {
      const that = this
      let defer = $.Deferred()
      http.get(constant.carsCategories, null, function(response) {
        that.carsCategories =  response.setCategories
        let array = Object.keys(response.setCategories).map(key=> response.setCategories[key])
        defer.resolve()
        //that.$set(that.$data, 'setCategories', array)
      }, function(response) {
        console.log(response)
      })
      return defer.promise()
    },

    resetModal() {
      this.$set(this.$data, 'selectedCountry', '')
      this.$set(this.$data, 'selectedCountryId', '')
      this.$set(this.$data, 'selectedCountryName', '')
      this.$set(this.$data, 'currentCountryId', '')
      this.$set(this.$data, 'currentCountryIndex', '')
    },

    bindSelectCountry(index, key, ev) {
      this.$nextTick(function () {
        this.$set(this.$data, 'selectedCountry', ev.currentTarget.getAttribute('data-country-code'))
        this.$set(this.$data, 'selectedCountryId', ev.currentTarget.getAttribute('data-country-id'))
        this.$set(this.$data, 'selectedCountryName', ev.currentTarget.getAttribute('data-country-name'))
        this.$set(this.$data, 'currentCountryIndex', index)
        this.$set(this.$data, 'currentCountryId', key)
        this.$set(this.$data, 'suppliersArray', ev.currentTarget.getAttribute('data-suppliers'))
      })
    },

    selectCitiesLetter(index) {
      console.log(index)
      this.$set(this.$data, 'currentLetter', index)
    },

    selectHotCitiesLetter(index) {
      this.$set(this.$data, 'currentHotLetter', index)
    },

    onSearchBrand(value) {
      let _this = this
      var values = this.selectedCountry
      if (values === '') {
        console.log('未选中国家')
        this.$root.$emit('bv::show::tooltip', 'countryEle')
        setTimeout(function() {
          _this.closeTooltip()
        }, 1500)
      } else {
        this.$set(this.$data, 'supplierDrop', false)
      }
    },

    hotCitiesShow(key) {
      const that = this
      let countryValues = this.selectedCountry
      let supplierValues = this.selectedsupplier.code
     
      if (countryValues === '') {
        this.$root.$emit('bv::show::tooltip', 'countryEle')
        setTimeout(function() {
          that.closeTooltip()
        }, 1500)
        return
      } else if (supplierValues === '') {
        this.$root.$emit('bv::show::tooltip', 'brandEle')
        setTimeout(function() {
          that.closeTooltip()
        }, 1500)
        return
      } else {
        that.requestHotCities(key);
        this.$refs['city-modal'].show()
      }
    },

    requestHotCities(value) {
      const that = this
      let parma = {
        'country': that.$data.selectedCountry,
        'brand': that.$data.selectedsupplier.code
      }
      
      http.get(constant.hotLocation, parma, function(response) {
        that.$set(that.$data, 'hotLocations', response.locations)
        that.$set(that.$data, 'currentShowModal', value)
      }, function(result) {
        console.log(result)
      })
    },

    bindSelectCity(index, key, ev) {
      
      if (this.currentShowModal === 'pickup') {
        this.selectedCityName= ev.currentTarget.getAttribute('data-city-name')
        this.selectedCityCode= ev.currentTarget.getAttribute('data-city-code')
        this.selectedCityId= ev.currentTarget.getAttribute('data-city-id')
        this.currentCityIndex= index
        this.currentCityId= key     
      } else if (this.currentShowModal === 'return') {
        this.returnCityName= ev.currentTarget.getAttribute('data-city-name')
        this.returnCityCode= ev.currentTarget.getAttribute('data-city-code')
        this.returnCityId= ev.currentTarget.getAttribute('data-city-id')
        this.returnCurrentCityIndex= index
        this.returnCurrentCityId= key
      }

      this.$refs['city-modal'].hide()
    },

    bindSearchCity(index, ev) {
      if (this.currentShowModal === 'pickup') {
        
        this.selectedCityName = ev.currentTarget.getAttribute('data-city-name')
        this.selectedCityCode = ev.currentTarget.getAttribute('data-city-code')
        this.selectedCityId = ev.currentTarget.getAttribute('data-city-id')
        this.currentSearchCityIndex = index
      } else if (this.currentShowModal === 'return') {
        
        this.returnCityName = ev.currentTarget.getAttribute('data-city-name')
        this.returnCityCode = ev.currentTarget.getAttribute('data-city-code')
        this.returnCityId = ev.currentTarget.getAttribute('data-city-id')
        this.returnCurrentSearchCityIndex = index
      }
      this.$refs['city-modal'].hide()
    },

    searchCity() {
      const that = this
      let country = this.selectedCountry
      let brand = this.selectedsupplier.code
      let codeString = this.searchCityVal
      let parma = {
        'country': country,
        'brand': brand,
        'code': codeString
      }
      that.$set(that.$data, 'searchCityData', '')
      
      if(this.searchCityVal && this.searchCityVal.length >=2) {
        http.get(constant.searchLocation, parma, function(response) {
          if(response.locations && response.locations.length >= 1) {
            that.$set(that.$data, 'searchCityData', response.locations)
            console.log(that.searchCityData)
          }
        }, function() {
         
        })
      } else {
        console.log()
      }
    },

    doSomethingOnClose() {
      console.log(this.pickupDate)
    },

    onSearchType(value) {
      let _this = this
      let countryValues = this.selectedCountry
      let supplierValues = this.selectedsupplier.code
      let pickupSiteValues = this.selectedPickupSite
      let returnSiteValues = this.selectedReturnSite
      if (countryValues === '') {
        this.$root.$emit('bv::show::tooltip', 'countryEle')
        setTimeout(function() {
          _this.closeTooltip()
        }, 1500)
        return
      } else if (supplierValues === '') {
        this.$root.$emit('bv::show::tooltip', 'brandEle')
        setTimeout(function() {
          _this.closeTooltip()
        }, 1500)
        return
      } else if (pickupSiteValues === '') {
        this.$root.$emit('bv::show::tooltip', 'pickupSiteEle')
        setTimeout(function() {
          _this.closeTooltip()
        }, 1500)
        return
      } else if (returnSiteValues === '') {
        this.$root.$emit('bv::show::tooltip', 'returnSiteEle')
        setTimeout(function() {
          _this.closeTooltip()
        }, 1500)
        return
      }
      
      this.generateData()
      this.$set(this.$data, 'typeDrop', false)
    },

    generateData() {
      // 根据 countryCode 和 suppliersId 获取付款方式
      // let countryCode = this.selectedCountry.split(",")
      let countryCode = this.selectedCityCode ? this.selectedCityCode.split(",") : this.selectedCountry.split(",")
      let suppliersId = this.selectedsupplier.id
      let carsCountrySets = []
      let payArr = []
      for(let i in countryCode) {
        carsCountrySets.push(this.carsSets[countryCode[i]][suppliersId])
      }
      
      for(let j in carsCountrySets) {
        for(let index in carsCountrySets[j]) {
          let paytype = carsCountrySets[j][index].pay_type
          var obj = {}

          if (paytype && paytype === 'ARRIVEPAY') {
            obj.payCode = 'ARRIVEPAY'
            obj.payName = '到付'
            payArr.push(obj)
          } else if(paytype && paytype != 'ARRIVEPAY') {
            obj.payCode = 'PREPAY'
            obj.payName = '预付'
            payArr.push(obj)
          }
        }
      }

      let newPyaArr= {};
  
      payArr = payArr.reduce(function(item, next) {
        newPyaArr[next.payCode] ? '' : newPyaArr[next.payCode] = true && item.push(next);
        return item
      }, [])

      this.typeOptions = payArr
    },

    onSearchCategories(value) {
      let _this = this
      let countryValues = this.selectedCountry
      let supplierValues = this.selectedsupplier.id
      let pickupSiteValues = this.selectedPickupSite
      let returnSiteValues = this.selectedReturnSite
      let typeValues = this.selectedType
      if (countryValues === '') {
        this.$root.$emit('bv::show::tooltip', 'countryEle')
        setTimeout(function() {
          _this.closeTooltip()
        }, 1500)
        return
      } else if (supplierValues === '') {
        this.$root.$emit('bv::show::tooltip', 'brandEle')
        setTimeout(function() {
          _this.closeTooltip()
        }, 1500)
        return
      } else if (pickupSiteValues === '') {
        this.$root.$emit('bv::show::tooltip', 'pickupSiteEle')
        setTimeout(function() {
          _this.closeTooltip()
        }, 1500)
        return
      } else if (returnSiteValues === '') {
        this.$root.$emit('bv::show::tooltip', 'returnSiteEle')
        setTimeout(function() {
          _this.closeTooltip()
        }, 1500)
        return
      } else if (typeValues === '') {
        this.$root.$emit('bv::show::tooltip', 'typeEle')
        setTimeout(function() {
          _this.closeTooltip()
        }, 1500)
        return
      }
      this.generateCategoriesData()
      this.$set(this.$data, 'categoriesDrop', false)
    },

    generateCategoriesData() {
      // 根据 countryCode 和 suppliersId payId 获取套餐
      // let countryCode = this.selectedCountry.split(",")
      let countryCode = this.selectedCityCode ? this.selectedCityCode.split(",") : this.selectedCountry.split(",")
      let suppliersId = this.selectedsupplier.id
      let carsCountrySets = []
      let categotyArr = []
      for(let i in countryCode) {
        carsCountrySets.push(this.carsSets[countryCode[i]][suppliersId])
      }

      for (let j in carsCountrySets) {
        for (let index in carsCountrySets[j]) {
          let pay_type = carsCountrySets[j][index].pay_type == 'ARRIVEPAY' ? 'ARRIVEPAY' : 'PREPAY'
          let categotyId = carsCountrySets[j][index].categoty
          if( pay_type === this.selectedType && categotyArr.indexOf(categotyId) == -1){
            categotyArr.push(categotyId);
          }
        }
      }

      let categoriesOpt = []
      for (let key of categotyArr) {
        categoriesOpt.push(this.carsCategories[key])
      }
      this.$set(this.$data, 'setCategories', categoriesOpt)
      // this.$set(this.$data, 'selectCategories', parseInt(this.$route.query.setCategoryId))
      //  this.selectedCategoryVal = parseInt(this.$route.query.setCategoryId)
    },

    searchResult: function () {
      let that = this

      let countryName = this.selectedCountryName
      let countryId = this.selectedCountryId
      let countryCode = this.selectedCountry
      let supplierId = this.selectedsupplier.id
      let pickupLocation = this.selectedCityId
      let returnLocation = this.returnCityId
      let pickupDate = this.pickupDate 
      let returnDate = this.returnDate
      // console.log('年龄',this.ageSelected.toString().indexOf("岁") > 0)
      let driveAge = this.ageSelected.toString().indexOf("岁") > 0 ? this.ageSelected.replace(/岁/g,'') : this.ageSelected
      let type = this.selectedType
      let setCategoryId = this.selectCategories

      if(!countryId || !countryCode || !supplierId || !pickupLocation || !returnLocation || !pickupDate || !returnDate || !driveAge || !type || !setCategoryId) {
        this.$message.error({
          message: '请完善表单',
          align: 'center'
        })
        return 
      }
      
      let parma = {
        filter: true,
        countryName: countryName,
        countryId: countryId,
        countryCode: countryCode,
        supplierId: supplierId,
        pickupLocation: pickupLocation,
        returnLocation: returnLocation,
        pickupDate: pickupDate, 
        returnDate: returnDate,
        driveAge: driveAge,
        type: type,
        setCategoryId: setCategoryId,
        mobile: this.$store.getters.getMobile
        //mobile: '17630050523'
      }
      let mobile = this.$store.getters.getMobile
      if (mobile) {
        // 已登录
        parma.mobile = mobile
      } else {
        // 未登录
        parma.login = false
      }

      let message = this.$message.loading({
        message: '正在加载数据...',
        align: 'center'
      })
      http.get('/cars', parma, data => {
        this.result = data
        this.defaultSort = data.vehicleCores
        this.carTypeOpt = this.carTypeOpt.concat(data.vehicleCategories)
        message.close()
      }, error => {
        message.close()
        this.result = {}
        this.defaultSort = []
        this.carTypeOpt = []
        this.$message.error({
          message: error.message,
          align: 'center'
        })
      })
    },

    filterCars() {
      event.preventDefault()
      this.$nextTick(function () {
        let that = this
        let data = that.result.vehicleCores
        let siteArr = that.selectedSiteVal.split(',')
        that.vehicleCores = data.filter(function(item) {
          if(that.selectedTypeVal == 0) {
            if(that.selectedSiteVal == '0,100') {
              return item
            } else {
              return parseInt(item.passenger_quantity) >= siteArr[0] && parseInt(item.passenger_quantity) < siteArr[1]
            }
          } else {
            return (item.category_code == that.selectedTypeVal) && (parseInt(item.passenger_quantity) >= siteArr[0] && parseInt(item.passenger_quantity) < siteArr[1])
          }
        })

        if (this.selectedPriceVal == 'default') {
          this.defaultSort = that.vehicleCores
        }
        that.hasVehicleCores = true
      })
    },

    appendCarPrice() {
      event.preventDefault();
      this.$nextTick(function () {
        let that = this
        let data = (that.vehicleCores && that.hasVehicleCores) ? that.vehicleCores : that.result.vehicleCores

        if(this.selectedPriceVal == 'LowToHigh') {
          data.sort((a,b)=>a.total_amount-b.total_amount)
        } else if(this.selectedPriceVal == 'highToLow') {
          data.sort((a,b)=>a.total_amount-b.total_amount).reverse()
        } else {
          data = this.defaultSort
        }
        that.vehicleCores = data
      })
    },

    togglePriceStatu() {
      this.priceStatu = !this.priceStatu
    },
    
    gotoLoginPage() {
      debugger
      this.$router.push({name: 'login', query: {redirect: this.$route.fullPath}})

    },

    showDescription(value) {
      this.$set(this.$data, 'showT', value)
    },

    closeTooltip() {
      this.$root.$emit('bv::hide::tooltip')
    },
  },
  mounted: function () {
    let that = this
    // this.searchResult()
    this.$nextTick(function () {
      this.$root.$on('bv::modal::hide', (bvEvent, modalId) => {
        // 根据国家选择相应套餐
        if (modalId === 'countryModal' && that.suppliersArray && that.suppliersArray != undefined) {
          let suppliersOption = that.suppliersArray.split(',')
          let suppliers = []
          for (let key in that.suppliersData) {
            for (let k in suppliersOption) {
              if (key === suppliersOption[k]) {
                suppliers.push(that.suppliersData[key])
              }
            }
          }
          that.$set(this.$data, 'suppliers', suppliers)
        }
      })
      this.$root.$on('bv::modal::show', (bvEvent, modalId) => {
        
        if(modalId === 'city-modal') {
          this.$set(this.$data, 'searchCityVal', "")
          this.$set(this.$data, 'hotCityShow', false)
          this.searchCityData = ''
        }
      })
    })
  },

  props: {
    carDetailData: Object,
    from: Object
  },

  watch: {
    selectedCountryName(curVal, oldVal) {
      if(this.loadingData) {
        this.selectedsupplier = ''
        this.selectedCityName = ''
        this.returnCityName = ''
        this.selectedType = null
        this.selectCategories = null
        this.$refs.typeSelect.clearSelection();    
        this.$refs.categorySelect.clearSelection();  
      }
    },
    selectedCityName() {
      console.log('r',this.returnCityId)
      if(this.returnCityId === undefined) {
        this.$set(this.$data, 'returnCityName', this.selectedCityName)
        this.$set(this.$data, 'returnCityCode', this.selectedCityCode)
        this.$set(this.$data, 'returnCityId', this.selectedCityId)
        this.$set(this.$data, 'returnCurrentCityIndex', this.currentCityIndex)
        this.$set(this.$data, 'returnCurrentCityId', this.currentCityId)
      }
    },
    searchCityVal(curVal) {
      if(curVal.length >=2 ) {
        this.searchCity()
      } else {
        this.searchCityData = ''
      }
    },
    '$route' (to, from){
      if(to.query && Object.keys(to.query).length > 0 && !to.query.redirect && to.name === 'searchResult') {
        this.selectedCountryName = this.$route.query.countryName
        this.selectedCountry = this.$route.query.countryCode
        this.selectedCountryId = this.$route.query.countryId
        this.selectedsupplier.id = this.$route.query.supplierId
        this.selectedCityId = this.$route.query.pickupLocation
        this.returnCityId = this.$route.query.returnLocation
        this.pickupDate  = this.$route.query.pickupDate
        this.returnDate = this.$route.query.returnDate
        this.ageSelected = this.$route.query.driveAge+'岁'
        this.selectedType = this.$route.query.type
        this.selectedCityName = this.$route.params.pickCityCode
        this.returnCityName = this.$route.params.returnCityCode
        this.$set(this.$data, 'selectCategories', parseInt(this.$route.query.setCategoryId))
        this.searchResult()
      }
    }
  }
}
